package com.rop.znyx.acl.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rop.znyx.acl.mapper.AdminMapper;
import com.rop.znyx.acl.mapper.AdminRoleMapper;
import com.rop.znyx.model.acl.Admin;
import com.rop.znyx.model.acl.AdminRole;
import com.rop.znyx.acl.service.AdminService;
import com.rop.znyx.vo.acl.AdminQueryVo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Title: AdminServiceImpl
 * @Author Rop
 * @Date 2023/6/13 23:14
 * @description: 用户管理业务实现层
 */

@Service
@RequiredArgsConstructor
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    private final AdminRoleMapper adminRoleMapper;

    /**
     * 获取用户分页列表
     *
     * @param pageParam    分页参数
     * @param adminQueryVo 查询参数
     * @return 查询结果
     */
    @Override
    public IPage<Admin> selectPage(Page<Admin> pageParam, AdminQueryVo adminQueryVo) {
        // 用户名
        String username = adminQueryVo.getUsername();
        // 昵称
        String name = adminQueryVo.getName();

        LambdaQueryWrapper<Admin> adminWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.isNotBlank(username)) {
            adminWrapper.like(Admin::getUsername, username);
        }

        if (StringUtils.isNotBlank(name)) {
            adminWrapper.like(Admin::getName, name);
        }

        return baseMapper.selectPage(pageParam, adminWrapper);
    }

    /**
     * 分配角色
     *
     * @param id 用户id
     * @return 分配结果
     */
    @Override
    @Transactional
    public Boolean doAssign(Long id, Long[] roleIds) {
        // 1.删除旧角色
        LambdaQueryWrapper<AdminRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdminRole::getAdminId, id);
        int deleteRows = adminRoleMapper.delete(queryWrapper);

        // 2.新增选中的角色
        if (ArrayUtil.isNotEmpty(roleIds)) {
            adminRoleMapper.batchInsert(id, roleIds);
        }

        return Boolean.TRUE;
    }
}
